package com.oriental.manage.controller.report;

import com.oriental.clearDubbo.model.base.RequestModel;
import com.oriental.clearDubbo.model.base.ResponseModel;
import com.oriental.clearDubbo.model.clear.report.ReportFormsModel;
import com.oriental.manage.core.excelUtils.ExcelTemplateUtil;
import com.oriental.manage.core.exception.BusiException;
import com.oriental.manage.core.fileUtils.ExcelContentExt;
import com.oriental.manage.core.fileUtils.FileDownAjax;
import com.oriental.manage.core.fileUtils.HeaderExt;
import com.oriental.manage.core.paging.Pagination;
import com.oriental.manage.core.response.ResponseDTO;
import com.oriental.manage.core.system.Constants;
import com.oriental.manage.core.system.log.OperateLogger;
import com.oriental.manage.core.utils.Bean2MapUtil;
import com.oriental.manage.core.utils.DateUtils;
import com.oriental.manage.pojo.institution.OrganizeInfo;
import com.oriental.manage.pojo.report.BankTransDetailReportData;
import com.oriental.paycenter.commons.mode.Response;
import com.oriental.settlementfront.service.facade.manager.BankTransDetailFacade;
import com.oriental.settlementfront.service.facade.manager.model.BankTransDetailDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.webbuilder.office.excel.config.ExcelWriterConfig;
import org.webbuilder.office.excel.config.Header;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <ul>
 * <li>支付指令核对日报表</li>
 * <li>User:zhangxinhai Date:2017/4/18 Time:15:15</li>
 * </ul>
 */
@Slf4j
@Controller
@RequestMapping("/report/bankTransDetailReport")
public class BankTransDetailReportController {

    @Autowired
    private BankTransDetailFacade bankTransDetailFacade;
    @Autowired
    private FileDownAjax fileDownAjax;
    @Autowired
    private Constants Constants;

    @RequestMapping("initBankTransDetail")
    public String initBankTransDetail() {
        return "report/searchBankTransDetailReport";
    }

    @RequestMapping("initFailure")
    public String initFailure() {
        return "report/searchBankTransDetailFailureReport";
    }

    @OperateLogger(content = "查询支付指令核对日报表", operationType = OperateLogger.OperationType.R)
    @RequestMapping("search")
    @RequiresPermissions("bankTransDetailReport_search")
    @ResponseBody
    public ResponseDTO<List<BankTransDetailReportData>> search(@RequestBody BankTransDetailReportData quey) {
        ResponseDTO<List<BankTransDetailReportData>> responseDTO = new ResponseDTO<>();
        log.info("查询信息:{}", quey);
        try {
            BankTransDetailDTO bankTransDetailDTO = new BankTransDetailDTO();
            bankTransDetailDTO.setTransConfirmDate(quey.getTransConfirmDate());
            //调用接口获取数据
            Response<List<BankTransDetailDTO>> response = bankTransDetailFacade.selectBankTransDetailList(bankTransDetailDTO);
            if (!response.isSuccess()) {
                throw new BusiException(response.getErrorCode(), response.getErrorMsg());
            }
            //对数据进行处理保存到map集合
            Map<String,List<BankTransDetailDTO>> map = new HashMap<>();
            for(BankTransDetailDTO bankTransDetailDTO1 : response.getResult()){
                List<BankTransDetailDTO> list = map.get(bankTransDetailDTO1.getPayOrgCode());
                if(list == null){
                    list = new ArrayList<>();
                    list.add(bankTransDetailDTO1);
                    map.put(bankTransDetailDTO1.getPayOrgCode(),list);
                }else {
                    list.add(bankTransDetailDTO1);
                }
            }
            //对map集合数据进行处理，对同一机构交易请求、成功、失败的笔数和金额进行赋值
            List<BankTransDetailReportData> bankTransDetailReportDataList = new ArrayList<>();
            //统计合计
            BankTransDetailReportData sumData = new BankTransDetailReportData();
            for (String key : map.keySet()){
                List<BankTransDetailDTO> list = map.get(key);
                BankTransDetailReportData bankTransDetailReportData = new BankTransDetailReportData();
                for(BankTransDetailDTO bankTransDetailDTO1 : list){
                    bankTransDetailReportData.setPayOrgCode(bankTransDetailDTO1.getPayOrgCode());
                    bankTransDetailReportData.setTransConfirmDate(bankTransDetailDTO1.getTransConfirmDate());
                    if(bankTransDetailDTO1.getTransStatus().equals(bankTransDetailReportData.getTransStatusA())){
                        bankTransDetailReportData.setTransCountA(bankTransDetailDTO1.getTransCount());
                        bankTransDetailReportData.setTransAmtA(bankTransDetailDTO1.getTransAmt());
                        sumData.setTransCountA(bankTransDetailDTO1.getTransCount() + sumData.getTransCountA());
                        sumData.setTransAmtA(bankTransDetailDTO1.getTransAmt() + sumData.getTransAmtA());
                    }else if(bankTransDetailDTO1.getTransStatus().equals(bankTransDetailReportData.getTransStatusB())){
                        bankTransDetailReportData.setTransCountB(bankTransDetailDTO1.getTransCount());
                        bankTransDetailReportData.setTransAmtB(bankTransDetailDTO1.getTransAmt());
                        sumData.setTransCountB(bankTransDetailDTO1.getTransCount() + sumData.getTransCountB());
                        sumData.setTransAmtB(bankTransDetailDTO1.getTransAmt() + sumData.getTransAmtB());
                    }else if(bankTransDetailDTO1.getTransStatus().equals(bankTransDetailReportData.getTransStatusC())){
                        bankTransDetailReportData.setTransCountC(bankTransDetailDTO1.getTransCount());
                        bankTransDetailReportData.setTransAmtC(bankTransDetailDTO1.getTransAmt());
                        sumData.setTransCountC(bankTransDetailDTO1.getTransCount() + sumData.getTransCountC());
                        sumData.setTransAmtC(bankTransDetailDTO1.getTransAmt() + sumData.getTransAmtC());
                    }else {
                        bankTransDetailReportData.setTransCountA(bankTransDetailDTO1.getTransCount());
                        bankTransDetailReportData.setTransAmtA(bankTransDetailDTO1.getTransAmt());
                        sumData.setTransCountA(bankTransDetailDTO1.getTransCount() + sumData.getTransCountA());
                        sumData.setTransAmtA(bankTransDetailDTO1.getTransAmt() + sumData.getTransAmtA());
                    }
                }
                bankTransDetailReportDataList.add(bankTransDetailReportData);
            }
            responseDTO.setSuccess(true);
            responseDTO.setObject(bankTransDetailReportDataList);
            responseDTO.setSumObject(sumData);
        } catch (BusiException e) {
            log.error("查询失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("查询失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg("系统繁忙");
        }
        return responseDTO;
    }

    @RequestMapping("searchFailure")
    @RequiresPermissions("bankTransDetailReport_searchFailure")
    @ResponseBody
    public ResponseDTO<Pagination<BankTransDetailDTO>> searchFailure(@RequestBody Pagination<BankTransDetailReportData> pagination) {
        ResponseDTO<Pagination<BankTransDetailDTO>> responseDTO = new ResponseDTO<>();
        log.info("查询信息:{}", pagination);
        try {
            BankTransDetailDTO bankTransDetailDTO = new BankTransDetailDTO();
            bankTransDetailDTO.setPayOrgCode(pagination.getQueryBean().getPayOrgCode());
            bankTransDetailDTO.setTransConfirmDate(pagination.getQueryBean().getTransConfirmDate());
            bankTransDetailDTO.setTransStatus(pagination.getQueryBean().getTransStatusC());
            bankTransDetailDTO.setStartRow(pagination.getStartRow());
            bankTransDetailDTO.setPageSize(pagination.getPageSize());
            //调用接口获取数据
            Response<com.oriental.settlementfront.service.facade.common.model.Pagination<BankTransDetailDTO>> response = bankTransDetailFacade.selectBankTransDetailFailureList(bankTransDetailDTO);
            if (!response.isSuccess()) {
                throw new BusiException(response.getErrorCode(), response.getErrorMsg());
            }
            Pagination<BankTransDetailDTO> pagination1 = new Pagination<>();
            pagination1.setRowCount(response.getResult().getTotalCount());
            pagination1.setList(response.getResult().getPageList());
            pagination1.setPageCount(pagination.getPageCount());
            pagination1.setPageNum(pagination.getPageNum());
            pagination1.setPageSize(pagination.getPageSize());
            responseDTO.setSuccess(true);
            responseDTO.setObject(pagination1);
        } catch (BusiException e) {
            log.error("查询失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("查询失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg("系统繁忙");
        }
        return responseDTO;
    }

    /**
     * 亿付数字支付机构、商户侧日结平衡表
     *
     * @param quey
     * @return
     */
    @RequestMapping("download")
    @ResponseBody
    public ResponseEntity<byte[]> download(@RequestBody BankTransDetailReportData quey) {
        ResponseEntity<byte[]> responseEntity;
        File tempFile = null;
        try {
            InputStream inputStream = new FileInputStream(Constants.getExcelPath() + "/支付指令核对日报表.xlsx");
            tempFile = fileDownAjax.touch("支付指令核对日报表-" + DateUtils.now() + ".xlsx");
            String time=new SimpleDateFormat("yyyy年MM月dd日").format(quey.getTransConfirmDate());
            ResponseDTO<List<BankTransDetailReportData>> responseDTO = this.search(quey);
            //表头
            LinkedList<Header> tHeaders = new LinkedList<>();
            //内容
            List<Object> datas = new ArrayList<>();
            //添加表头
            tHeaders.add(new HeaderExt("渠道名称", "payOrgCode", ExcelContentExt.ORGANIZE));
            tHeaders.add(new HeaderExt("笔数", "transCountSum"));
            tHeaders.add(new HeaderExt("金额", "transAmtSum",ExcelContentExt.CURRENCY));
            tHeaders.add(new HeaderExt("笔数", "transCountVerify"));
            tHeaders.add(new HeaderExt("金额", "transAmtVerify",ExcelContentExt.CURRENCY));
            tHeaders.add(new HeaderExt("笔数", "transCountB"));
            tHeaders.add(new HeaderExt("金额", "transAmtB",ExcelContentExt.CURRENCY));
            tHeaders.add(new HeaderExt("笔数", "transCountC"));
            tHeaders.add(new HeaderExt("金额", "transAmtC",ExcelContentExt.CURRENCY));

            for (BankTransDetailReportData bankTransDetailReportData : responseDTO.getObject()) {
                Map map = Bean2MapUtil.convertBean(bankTransDetailReportData);
                datas.add(map);
            }
            BankTransDetailReportData bankTransDetailReportData = (BankTransDetailReportData)responseDTO.getSumObject();
            bankTransDetailReportData.setPayOrgCode("合计");
            Map map = Bean2MapUtil.convertBean(bankTransDetailReportData);
            datas.add(map);
            ExcelWriterConfig config = new ExcelWriterConfig();
            config.setHeaders(tHeaders);
            config.setDatas(datas);
            config.setStartWith(5);
            FileOutputStream outputStream = new FileOutputStream(tempFile);
            ExcelTemplateUtil.writeTitle(inputStream,outputStream,config,time);
            responseEntity = fileDownAjax.getResponseEntity(tempFile);
        } catch (Exception e) {
            log.error("下载失败", e);
            responseEntity = fileDownAjax.getResponseEntityFail();
        } finally {
            fileDownAjax.forceDelete(tempFile);
        }
        return responseEntity;
    }
}
